/**
 * This file is part of AppStoreBot.
 *
 *  AppStoreBot is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  AppStoreBot is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with AppStoreBot.  If not, see <http://www.gnu.org/licenses/>.
 *
 */
package lu.pragmaconsult.appstorebot.itunes;

import static lu.pragmaconsult.appstorebot.itunes.Constants.AJAX_NAME;
import static lu.pragmaconsult.appstorebot.itunes.Constants.ATT_ID;
import static lu.pragmaconsult.appstorebot.itunes.Constants.DEFAULT_VENDOR_PAGE;
import static lu.pragmaconsult.appstorebot.itunes.Constants.SALES_AND_TREND;
import static lu.pragmaconsult.appstorebot.itunes.Constants.VIEW_STATE;
import static lu.pragmaconsult.appstorebot.itunes.Constants.XPATH_INPUT;
import static lu.pragmaconsult.appstorebot.itunes.Constants.XPATH_SCRIPT;

import java.io.IOException;

import javax.xml.xpath.XPathConstants;

import lu.pragmaconsult.appstorebot.BotContext;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * TODO: Type comment
 * @author Wilfried Vandenberghe (wilfried.vandenberghe at pragmaconsult.lu)
 */
class SalesAndTrendBotState extends AbstractBotState {
	
	@Override
	protected HttpMethod createHttpMethod(BotContext context, HttpClient httpClient) {
		return new GetMethod(context.getContextAttribute(SALES_AND_TREND));
	}
	
	@Override
	protected void processResponseBody(BotContext context, HttpMethod method) {
		try {
			HtmlParser parser = new HtmlParser(method.getResponseBodyAsStream());
			
			// get the view state value
			NodeList nodes = (NodeList) parser.evaluate(XPATH_INPUT, XPathConstants.NODESET);
			if (nodes == null) {
				throw new IllegalStateException("Cannot found view state");
			}
	
			for (int i = 0; i < nodes.getLength(); i++) {
				Node node = nodes.item(i);
				
				if(node.getAttributes().getNamedItem(ATT_ID) != null) {
					String id = node.getAttributes().getNamedItem(ATT_ID).getNodeValue();
					if("javax.faces.ViewState".equals(id)) {
						context.setContextAttribute(VIEW_STATE, node.getAttributes().getNamedItem("value").getNodeValue());
						break;
					}
				}
			}
			
			// get the defaultVendorPage and the ajax name
			nodes = (NodeList) parser.evaluate(XPATH_SCRIPT, XPathConstants.NODESET);
			if (nodes == null) {
				throw new Exception("Cannot found vendor");
			}
	
			for (int i = 0; i < nodes.getLength(); i++) {
				Node node = nodes.item(i);
				
				if(node.getAttributes().getNamedItem(ATT_ID) != null) {
					String script = node.getAttributes().getNamedItem(ATT_ID).getNodeValue();
					if(script.contains(DEFAULT_VENDOR_PAGE)) {
						String[] tokens = script.split(":");
						context.setContextAttribute(DEFAULT_VENDOR_PAGE, tokens[1]);
						context.setContextAttribute(AJAX_NAME, tokens[1].replaceFirst("_2", "_0"));
						break;
					}
				}
			}
		} catch (IOException e) {
			throw new IllegalStateException(e);
		} catch (Exception e) {
			throw new IllegalStateException(e);
		}
	}
	
	@Override
	protected BotState getNextState() {
		return new SalesAndTrendPageBotState();
	}
}
